package com.bxd.baodan.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.PopAdBean;
import com.bxd.baodan.item.ServiceItem;
import com.bxd.baodan.service.ImageService;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpKey;
import com.bxd.baodan.util.SpUtil;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.List;


public class WelcomeActivity extends FragmentActivity {
    private static final int SHOW_AD = 100;
    ImageView linear;
    private ImageView un_show_iv;

    private List<ServiceItem> list;
    private Button btn;
    boolean isStop = false; //循环截止标志
    int time = 3;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_AD:
                    //判断是否有广告,并加载
                    if (doScreenLoad() == -1) {
                        handler.postDelayed(run, 0);
                    } else {
                        btn.setVisibility(View.VISIBLE);
                        startTime();
                    }
                    break;
                default:
                    btn.setText("跳过->" + msg.what);
                    if (msg.what == 1) {
                        handler.postDelayed(run, 0);
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.welcome);
        AppManager.getInstance().addActivity(this);

        //  upLoadProbe();

        un_show_iv = (ImageView) findViewById(R.id.un_show_iv);


        if (LoginInfo.getInstance(this).isWelFirst()) {
            startActivity(new Intent(this, MainActivity.class));
            // FIXME: 18/1/31 解决短暂黑屏的问题
            //  finish();


        } else {
            setOnClick();
            startService(new Intent(this, ImageService.class));//下载图片
            handler.sendEmptyMessageDelayed(SHOW_AD, 1000);  //判断是否有广告,并加载
        }
//首页弹窗用
        getPopAdData();
    }

    private void getPopAdData() {

        NetUtil netUtil = new NetUtil(this, JsonApi.COMMON_POPADS);

        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {

                String str = JSONUtil.getData("list", data);
                String preData = SpUtil.getInstance().getString(SpKey.POP_AD);
                if (!(preData != null && preData.equals(str))) {
                    SpUtil.getInstance().savaString(SpKey.POP_AD_TIME, "");
                    SpUtil.getInstance().savaBoolean(SpKey.POP_AD_CLOSE, false);
                    SpUtil.getInstance().savaBoolean(SpKey.POP_AD_OPEN, false);

                }

                SpUtil.getInstance().savaString(SpKey.POP_AD, str);
                PopAdBean bean = GsonUtil.fromJson(str, PopAdBean.class);

                if (bean == null) {

                    SpUtil.getInstance().savaString(SpKey.POP_AD_TIME, "");
                    SpUtil.getInstance().savaBoolean(SpKey.POP_AD_CLOSE, false);
                    SpUtil.getInstance().savaBoolean(SpKey.POP_AD_OPEN, false);
                } else {
                    GlideUtil.loadImage(getApplicationContext(), bean.popupContent, un_show_iv);
                }
            }
        });


    }


    private void setOnClick() {
        linear = (ImageView) findViewById(R.id.linear_img);
        btn = (Button) findViewById(R.id.tiaoguo_btn);
        linear.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //启动页点击
                MobclickAgent.onEvent(App.getContext(), "v5_5_1_QDY");

                if (list != null && list.size() > 0) {
                    if (!list.get(0).getAdUrl().equals("")) {
                        handler.removeCallbacksAndMessages(null);
                        isStop = !isStop;

                        Intent mainPageIntent = new Intent(WelcomeActivity.this, MainActivity.class);
                        Intent webviewPageIntent = new Intent(WelcomeActivity.this,
                                WebViewPager.class).putExtra("startUrl", list
                                .get(0).getAdUrl());
                        Intent[] intents = new Intent[2];
                        intents[0] = mainPageIntent;
                        intents[1] = webviewPageIntent;
                        startActivities(intents);
                        // FIXME: 2017/12/29 原来添加了finish()方法,造成点击广告页的时候,WebViewPager还没有初始化,WelcomeActivity就会finish,用户不停点击,会因为回到桌面点击到并启动其他应用
                        // FIXME: 2017/12/29 原本是怕关闭应用,释放不掉WelcomeActivity,其实担心是多余的,因为退出app是在MainActivity中执行的,退出时会清理掉所以的Activity,不用担心WelcomeActivity.
                    }
                }
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                isStop = !isStop;
                handler.removeCallbacksAndMessages(null);

                btn.setVisibility(View.GONE);
                startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
                finish();
            }
        });

    }

    /**
     * 开始计时
     */
    private void startTime() {
        new Thread() {
            public void run() {
                while (time > 0 && !isStop) {
                    try {
                        if (handler == null) {
                            return;
                        }
                        handler.sendEmptyMessage(time--);
                        Thread.sleep(1 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    /**
     * 加载网络图片
     */
    private int doScreenLoad() {
        list = DBHelper.getInstance(App.getContext()).getServiceItem(); //获取ImageService中的广告信息
        if (list == null || list.size() == 0) {
            return -1; //表示数据库中没有广告信息,不展示广告
        }
        File fileDir = new File(Constant.IMAGE_AD); //ad目录
        File[] files = fileDir.listFiles();
        if (fileDir.exists() && files.length > 0) { //有文件
            String[] fileNames = new String[files.length];
            for (int j = 0; j < list.size(); j++) {
                String phpStartTime = list.get(j).getStartTime() + "";
                String phpEndTime = list.get(j).getEndTime() + "";
                long javaStartTime = Long.parseLong(phpStartTime + "000");
                long javaEndTime = Long.parseLong(phpEndTime + "000");

                for (int i = 0; i < files.length; i++) {
                    fileNames[i] = files[i].getName();

                    if (fileNames[i].equals(phpStartTime + "_" + phpEndTime + ".jpg")) {
                        //广告没过期
                        if (javaEndTime > System.currentTimeMillis()
                                && javaStartTime < System.currentTimeMillis()) {

                            Glide.with(WelcomeActivity.this).load(Constant.IMAGE_AD
                                    + fileNames[i]).into(linear);

                            return 0;
                        } else {
                            //过期图片删除
                            File f = new File(Constant.IMAGE_AD + fileNames[i]);
                            f.delete();
                        }
                    } else {
                        //名称不匹配删除
                        File f = new File(Constant.IMAGE_AD + fileNames[i]);
                        f.delete();
                    }
                }

            }
        }
        return -1;
    }

    Runnable run = new Runnable() {
        @Override
        public void run() {
            //进入首页
            handler.removeCallbacksAndMessages(null);
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
            finish();

        }
    };

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }




}
